<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="表名称" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input
          v-model="queryParams.tableComment"
          placeholder="请输入表描述"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Download" size="small" @click="handleGenTable"
          >生成</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" size="small" @click="openImportTable"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          size="small"
          :disabled="single"
          @click="handleEditTable"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <right-toolbar :showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="tablesRef"
      v-loading="loading"
      :data="tableList"
      @selection-change="handleSelectionChange"
      :default-sort="defaultSort"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template #default="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="表名称"
        align="center"
        prop="tableName"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column
        label="表描述"
        align="center"
        prop="tableComment"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column
        label="实体"
        align="center"
        prop="className"
        :show-overflow-tooltip="true"
        width="120"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        sortable="custom"
        :sort-orders="['descending', 'ascending']"
        width="160"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        sortable="custom"
        :sort-orders="['descending', 'ascending']"
        width="160"
      />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" size="small" icon="View" @click="handlePreview(scope.row)"
            >预览</el-button
          >
          <el-button type="text" size="small" icon="Edit" @click="handleEditTable(scope.row)"
            >编辑</el-button
          >
          <el-button type="text" size="small" icon="Delete" @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button type="text" size="small" icon="Refresh" @click="handleSynchDb(scope.row)"
            >同步</el-button
          >
          <el-button type="text" size="small" icon="Download" @click="handleGenTable(scope.row)"
            >生成代码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 预览界面 -->
    <el-dialog
      :title="preview.title"
      v-model="preview.open"
      width="80%"
      top="5vh"
      append-to-body
      class="scrollbar"
    >
      <el-tabs v-model="preview.activeName">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))"
          :key="key"
        >
          <el-link
            :underline="false"
            icon="DocumentCopy"
            @click="copyCode(value)"
            style="float: right"
            >复制</el-link
          >
          <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <import-table ref="importRef" @ok="handleQuery" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onActivated, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { listTable, previewTable, delTable, genCode, synchDb } from '@/api/tool/gen'
import importTable from './importTable.vue'
import 'highlight.js/styles/github-gist.css'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'

// 注册语言 - 修改为同步import方式
import hljs from 'highlight.js/lib/core'
import java from 'highlight.js/lib/languages/java'
import xml from 'highlight.js/lib/languages/xml'
import javascript from 'highlight.js/lib/languages/javascript'
import sql from 'highlight.js/lib/languages/sql'

// Register languages
hljs.registerLanguage('java', java)
hljs.registerLanguage('xml', xml)
hljs.registerLanguage('javascript', javascript)
hljs.registerLanguage('sql', sql)
// Since html, vue share the same xml language definition
hljs.registerLanguage('html', xml)
hljs.registerLanguage('vue', xml)

// 定义类型
interface Table {
  tableId?: string
  tableName?: string
  tableComment?: string
  className?: string
  createTime?: string
  updateTime?: string
  genType?: string
  genPath?: string
}

interface QueryParams {
  pageNum: number
  pageSize: number
  tableName?: string
  tableComment?: string
  orderByColumn?: string
  isAsc?: string
}

interface Preview {
  open: boolean
  title: string
  data: Record<string, string>
  activeName: string
}

// 引用
const queryFormRef = ref<FormInstance>()
const tablesRef = ref()
const importRef = ref<InstanceType<typeof importTable>>()

// 数据
const loading = ref(true)
const uniqueId = ref('')
const ids = ref<string[]>([])
const tableNames = ref<string[]>([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const tableList = ref<Table[]>([])
const dateRange = ref('')
const defaultSort = ref<{ prop: string; order: 'ascending' | 'descending' }>({
  prop: 'createTime',
  order: 'descending',
})

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  tableName: undefined,
  tableComment: undefined,
})

const preview = reactive<Preview>({
  open: false,
  title: '代码预览',
  data: {},
  activeName: 'domain.java',
})

// 路由
const route = useRoute()
const router = useRouter()

// 创建时执行
queryParams.orderByColumn = defaultSort.value.prop
queryParams.isAsc = defaultSort.value.order

// 激活时执行
onActivated(() => {
  const time = route.query.t
  if (time != null && time != uniqueId.value) {
    uniqueId.value = time as string
    queryParams.pageNum = Number(route.query.pageNum)
    getList()
  }
})

// 方法
/** 查询表集合 */
const getList = () => {
  loading.value = true
  listTable(addDateRange(queryParams, dateRange.value)).then((response) => {
    tableList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
// 加载时执行
getList()

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 生成代码操作 */
const handleGenTable: Fn = (row?: Table) => {
  const tableNamesValue = row?.tableName || tableNames.value
  if (!tableNamesValue || tableNamesValue.length === 0) {
    ElMessage.error('请选择要生成的数据')
    return
  }
  if (row?.genType === '1') {
    genCode(row.tableName!).then((response) => {
      ElMessage.success('成功生成到自定义路径：' + row.genPath)
    })
  } else {
    // 模拟下载功能
    const link = document.createElement('a')
    link.href = '/code/gen/batchGenCode?tables=' + tableNamesValue
    link.download = 'cj.zip'
    link.click()
  }
}

/** 同步数据库操作 */
const handleSynchDb = (row: Table) => {
  const tableName = row.tableName
  ElMessageBox.confirm('确认要强制同步"' + tableName + '"表结构吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return synchDb(tableName!)
    })
    .then(() => {
      ElMessage.success('同步成功')
    })
    .catch(() => {})
}

/** 打开导入表弹窗 */
const openImportTable = () => {
  importRef.value?.show()
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ''
  // 重置表单
  queryParams.tableName = undefined
  queryParams.tableComment = undefined
  queryParams.pageNum = 1
  // 这里需要根据实际项目中的排序方法来实现
  // tablesRef.value?.sort(defaultSort.value.prop, defaultSort.value.order)
  getList()
}

/** 预览按钮 */
const handlePreview = (row: Table) => {
  previewTable(row.tableId!).then((response) => {
    preview.data = response.data
    preview.open = true
    preview.activeName = 'domain.java'
  })
}

/** 高亮显示 */
const highlightedCode = (code: string, key: string) => {
  const vmName = key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'))
  const language = vmName.substring(vmName.indexOf('.') + 1, vmName.length)
  const result = hljs.highlight(language, code || '', true)
  return result.value || '&nbsp;'
}

/** 复制代码 */
const copyCode = (value: string) => {
  navigator.clipboard.writeText(value).then(() => {
    ElMessage.success('复制成功')
  })
}

// 多选框选中数据
const handleSelectionChange = (selection: Table[]) => {
  ids.value = selection.map((item) => item.tableId || '')
  tableNames.value = selection.map((item) => item.tableName || '')
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 排序触发事件 */
const handleSortChange = (column: any) => {
  queryParams.orderByColumn = column.prop
  queryParams.isAsc = column.order
  getList()
}

/** 修改按钮操作 */
const handleEditTable: Fn = (row?: Table) => {
  const tableId = row?.tableId || ids.value[0]
  const tableName = row?.tableName || tableNames.value[0]
  // 跳转到编辑页面
  router.push({
    path: '/tool/gen-edit/index/' + tableId,
    query: { pageNum: queryParams.pageNum.toString() },
  })
}

/** 删除按钮操作 */
const handleDelete: Fn = (row?: Table) => {
  const tableIds = row?.tableId || ids.value
  ElMessageBox.confirm('是否确认删除表编号为"' + tableIds + '"的数据项？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return delTable(tableIds)
    })
    .then(() => {
      getList()
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

// 辅助方法
const addDateRange = (params: any, dateRange: string) => {
  // 简化实现，实际项目中应该根据日期范围添加参数
  return { ...params }
}
</script>
